import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/app_fonts.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/general_dialog_content_widget.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/custom_button_widget.dart';
import 'package:leader_doctor_flutter/model/event/file_event.dart';
import 'package:leader_doctor_flutter/model/my_doctor_service_details_model.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/mine/page/event/refresh_event.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

class MyDoctorServiceDetailsPage extends StatefulWidget {
  const MyDoctorServiceDetailsPage({super.key, required this.listId});

  final String listId;

  @override
  State<MyDoctorServiceDetailsPage> createState() => _MyDoctorServiceDetailsPageState();
}

class _MyDoctorServiceDetailsPageState extends State<MyDoctorServiceDetailsPage> {
  MyDoctorServiceDetailsModel? detailsModel;

  final _textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _getDoctorServiceDetailsData(widget.listId);

    _textEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  /// 获取详情
  _getDoctorServiceDetailsData(String listId) async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.doctorServiceListDetails, body: {
      'id': listId,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);

    var serviceResult =
        ServiceResult<MyDoctorServiceDetailsModel>(httpResponse, (map) => MyDoctorServiceDetailsModel.fromJson(map));
    print("获取详情 = ${httpResponse.body}");
    if (serviceResult.success) {
      detailsModel = serviceResult.responseBody;
    }
    setState(() {});
  }

  /// 医生服务退款审核（2同意，3拒绝）
  _submitAuditServiceRefundData(String status) async {
    String auditResult = "";
    if (status == "3") {
      var text = _textEditingController.text;
      auditResult = text;
      if (text.isEmpty) {
        ToastUtils.showToast(context, '请输入拒绝理由');
        return;
      }
    }
    var user = App.instance.userInfo;
    String auditId = detailsModel?.refundAuditId ?? "";
    var httpRequest = HttpRequest(Api.auditServiceRefund, body: {
      'id': auditId,
      "status": status,
      "auditResult": auditResult,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<dynamic>.simple(httpResponse);
    print("是否同意退款申请 = ${httpResponse.body}");
    if (serviceResult.success) {
      App.instance.eventBus.fire(RefreshEvent());
      context.pop();
    }
    setState(() {
      _getDoctorServiceDetailsData(widget.listId);
    });
  }

  // 确认完成服务
  _confirmFinishService(String listId) async {
    var httpRequest = HttpRequest(Api.finishService, body: {
      'id': listId,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<dynamic>(httpResponse, (map) => null);
    print("确认完成服务 = ${httpResponse.body}");
    if (serviceResult.success) {
      App.instance.eventBus.fire(RefreshEvent());
    }
    setState(() {
      _getDoctorServiceDetailsData(listId);
    });
  }

  Widget contentView() {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              topStatusView(),
              purchaserInfoView(),
              Container(
                padding: EdgeInsets.only(right: 12.w, left: 12.w),
                child: SizedBox(
                  height: 1.w,
                  child: Container(color: Color(0xFFF2F2F2)),
                ),
              ),
              servicePackageInfoView(),
              SizedBox(
                height: 40.w,
              ),
              serviceOtherView(),
            ],
          ),
        ),
      ),
    );
  }

  // 顶部状态
  Widget topStatusView() {
    String status = detailsModel?.status ?? "";
    String? statusStr;
    String? iconStr;
    Color statusColor = ColorRes.color333333;
    if (status == "untreated" || status == "0") {
      // 未使用
      statusStr = "未使用";
      iconStr = "icon_doctor_service_no.webp";
      statusColor = ColorRes.color518DF6;
    } else if (status == "finish" || status == "1") {
      // 已使用
      statusStr = "已使用";
      iconStr = "icon_doctor_service_yes.webp";
      statusColor = Color(0xFF2AA515);
    } else if (status == "refund") {
      // 已退款
      statusStr = "已退款";
      iconStr = "icon_doctor_service_no.webp";
      statusColor = ColorRes.color333333;
    }

    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w),
      height: 55.w,
      width: double.infinity,
      color: ColorRes.colore6e6ff,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          iconStr == null
              ? Container()
              : ImageLoader.loadAsset(
                  iconStr,
                  20.w,
                ),
          SizedBox(
            width: 5.w,
          ),
          Text(
            statusStr ?? '',
            style: TextStyle(
              fontSize: 14.sp,
              color: statusColor,
            ),
          )
        ],
      ),
    );
  }

  // 购买人信息
  Widget purchaserInfoView() {
    String nameStr = detailsModel?.patientName ?? "";
    String sexStr = detailsModel?.sex ?? "";
    String ageStr = detailsModel?.age ?? "";
    sexStr = sexStr == "1" ? "男" : "女";
    String ageAndSex = sexStr + " | " + ageStr + "岁";
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w),
      height: 50.w,
      color: Colors.white,
      child: Column(
        // crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: "购买人：",
                      style: TextStyle(
                          color: ColorRes.color999999,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.medium),
                    ),
                    WidgetSpan(
                      child: SizedBox(
                        width: 1.w,
                      ),
                    ),
                    TextSpan(
                      text: "${nameStr}",
                      style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.bold),
                    ),
                    WidgetSpan(
                      child: SizedBox(
                        width: 8.w,
                      ),
                    ),
                    TextSpan(
                      text: "${ageAndSex}",
                      style: TextStyle(
                          color: ColorRes.color666666,
                          fontSize: 14.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.medium),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 服务包详情信息
  Widget servicePackageInfoView() {
    String imageUrlStr = detailsModel?.drugImage ?? "";
    String titleStr = detailsModel?.drugName ?? "";
    String descStr = detailsModel?.remark ?? "";
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 15.w),
      color: Colors.white,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(6.w), // 添加圆角
            child: ImageLoader.loadImage(imageUrlStr,
                size: Size(88.w, 88.w), fit: BoxFit.contain, errorImg: "assets/images/icon_default_img.webp"),
          ),
          SizedBox(
            width: 10.w,
          ),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                child: Text(
                  "${titleStr}",
                  style: TextStyle(
                      fontSize: 14.sp, color: Colors.black, fontFamily: AppFonts.pingFangSC, fontWeight: AppFonts.bold),
                ),
              ),
              SizedBox(
                height: 3.w,
              ),
              Text(
                "${descStr}",
                maxLines: 4, // 最大行数设置为5行
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                style: TextStyle(
                  fontSize: 12.sp,
                  color: ColorRes.color666666,
                ),
              ),
            ],
          ))
        ],
      ),
    );
  }

  // 服务费用等信息
  Widget serviceOtherView() {
    int servicePrice = detailsModel?.price ?? 0;
    String servicePriceStr = (servicePrice / 100).toStringAsFixed(2);
    String status = detailsModel?.status ?? "";
    String payStatus = detailsModel?.payStatus ?? "";
    String refundTime = detailsModel?.refundTime ?? "";
    String applyReason = detailsModel?.applyReason ?? "";
    String applyRefundTime = detailsModel?.applyRefundTime ?? "";
    String payTime = detailsModel?.payTime ?? "";
    String updateTime = detailsModel?.updateTime ?? "";
    // 等待患者确认
    String confirm = detailsModel?.confirm ?? "";
    String confirmStr = "";
    String noticeStr = "发起 “确认完成服务”，患者确认后，则完成该家医服务；如果患者未及时确认，7天后自动确认完成服务。";
    String psStr = "";

    // 第二行
    String twoTitleStr = "";
    // 第三行
    String threeTitleStr = "";
    // 第四行
    String fourTitleStr = "";
    // 第五行
    String fiveTitleStr = "";

    // 第二行
    String twoDescStr = "";
    // 第三行
    String threeDescStr = "";
    // 第四行
    String fourDescStr = "";
    // 第五行
    String fiveDescStr = "";

    if (payStatus == "toPay") {
      // 未支付
      psStr = noticeStr;
      confirmStr = confirm;
      print("confirm111 = ${confirm}");
    } else {
      if (status == "untreated" || status == "0") {
        // 未使用
        twoTitleStr = "购买时间";
        twoDescStr = payTime;
        psStr = noticeStr;
        confirmStr = confirm;
        if (payStatus == "refunding") {
          threeTitleStr = "申请退款时间";
          threeDescStr = refundTime;
        }
      } else if (status == "finish" || status == "1") {
        // 已使用
        twoTitleStr = "购买时间";
        twoDescStr = payTime;
        threeTitleStr = "服务完成时间";
        threeDescStr = updateTime;
      } else if (status == "refund") {
        // 已退款
        twoTitleStr = "购买时间";
        twoDescStr = payTime;
        threeTitleStr = "退款金额";
        threeDescStr = "¥${servicePriceStr}";
        fourTitleStr = "退款时间";
        fourDescStr = refundTime;
        fiveTitleStr = "退款原因";
        fiveDescStr = applyReason;
      }
    }

    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          serviceListView("服务费用", "¥${servicePriceStr}"),
          if (StringUtils.isNotEmpty(twoDescStr)) serviceListView("${twoTitleStr}", "${twoDescStr}"),
          if (StringUtils.isNotEmpty(threeDescStr)) serviceListView("${threeTitleStr}", "${threeDescStr}"),
          if (StringUtils.isNotEmpty(fourDescStr)) serviceListView("${fourTitleStr}", "${fourDescStr}"),
          if (StringUtils.isNotEmpty(fiveDescStr)) serviceListView("${fiveTitleStr}", "${fiveDescStr}"),
          if (StringUtils.isNotEmpty(psStr))
            Container(
              padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 10.w),
              child: Text(
                psStr,
                style: TextStyle(
                    fontSize: 12.sp,
                    color: ColorRes.color518DF6,
                    fontFamily: AppFonts.pingFangSC,
                    fontWeight: AppFonts.medium),
              ),
            ),
          initBottomBtnView(confirmStr, status, payStatus),
        ],
      ),
    );
  }

  Widget initBottomBtnView(String confirmStr, String status, String payStatus) {
    print("status = ${status}");
    Widget widget = Container();
    if (status == "untreated" || status == "0") {
      if (payStatus == "refunding") {
        // 展示 退款申请 底部多个按钮
        widget = initRefundApplicationBottomBtnView();
      } else if (status != "finish" && status != "refund") {
        if (StringUtils.isNotEmpty(status)) {
          // 展示 确认完成服务按钮
          widget = confirmFinishBtn(confirmStr, status, payStatus);
        }
      }
    } else if (status != "finish" && status != "refund") {
      if (StringUtils.isNotEmpty(status)) {
        // 展示 确认完成服务按钮
        widget = confirmFinishBtn(confirmStr, status, payStatus);
      }
    }
    return widget;
  }

  // confirmStr按钮状态，status订单状态，payStatus状态
  Widget confirmFinishBtn(String confirmStr, String status, String payStatus) {
    bool confirmStatus = true;
    String titleStr = "";
    print("confirmStr = ${confirmStr}");
    if (StringUtils.isNotEmpty(confirmStr) && confirmStr == "0") {
      confirmStatus = true;
      titleStr = "确定完成服务";
    } else if (StringUtils.isNotEmpty(confirmStr) && confirmStr == "1") {
      confirmStatus = false;
      titleStr = "等待患者确认中";
    }

    return Container(
      child: Container(
        padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 50.w),
        child: CommWidget.buildBtn2(
            Text(
              "${titleStr}",
              style: TextStyle(
                  fontSize: 14.sp, color: Colors.white, fontFamily: AppFonts.pingFangSC, fontWeight: AppFonts.medium),
            ), () {
          print("确定完成服务confirmStr = ${confirmStr}");
          if (confirmStatus == true && payStatus == "toPay") {
            Fluttertoast.showToast(msg: '患者未支付', gravity: ToastGravity.CENTER);
          } else {
            if (confirmStatus == true) {
              _confirmFinishServiceBottomDialog();
            }
          }
        }, ColorRes.colorMain, ColorRes.color4d0065ff, isSelect: confirmStatus),
      ),
    );
  }

  // 底部弹框文案 + 按钮
  _confirmFinishServiceBottomDialog() {
    return CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('请确定是否完成患者的服务',
                    style: TextStyle(fontWeight: FontWeight.normal, color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          print("取消");
                          c.pop();
                        },
                        child: Container(
                          height: 40.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6.w),
                            border: Border.all(
                              color: ColorRes.colorMain, // 设置边框颜色
                              width: 1.w, // 设置边框宽度
                            ),
                            color: Color(0xFFDDEBFF), // 添加背景色
                          ),
                          child: Text(
                            "取消",
                            style: TextStyle(fontSize: 14.sp, color: ColorRes.colorMain),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 15.w,
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          print("确定");
                          _confirmFinishService(widget.listId);
                          c.pop();
                        },
                        child: Container(
                          height: 40.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6.w),
                            color: ColorRes.colorMain,
                          ),
                          child: Text(
                            "确定",
                            style: TextStyle(fontSize: 14.sp, color: ColorRes.white),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ));
  }

  // 服务包List信息 + 分割线
  Widget serviceListView(String title, String desc) {
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w),
      height: 45.w,
      color: ColorRes.colorf5f5f5,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "${title}",
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: ColorRes.color999999,
                      fontFamily: AppFonts.pingFangSC,
                      fontWeight: AppFonts.medium),
                ),
                Text(
                  "${desc}",
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: ColorRes.color333333,
                      fontFamily: AppFonts.pingFangSC,
                      fontWeight: AppFonts.medium),
                ),
              ],
            ),
          ),
          Container(
            height: 0.5.w,
            color: Color(0xFFD2D2D2),
          ),
        ],
      ),
    );
  }

  // 申请退款列表详情 - 底部拒绝、同意退款、确定完成服务按钮UI
  Widget initRefundApplicationBottomBtnView() {
    return Container(
      padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 100.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: CustomButtonWidget(
              text: "拒绝退款",
              onTap: () {
                print("拒绝退款");
                _buildRefuseRefundDialog();
              },
              textStyle: TextStyle(fontSize: 14.sp, color: ColorRes.white),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: Color(0xFFFF2D55), // 添加背景色
              ),
            ),
          ),
          SizedBox(
            width: 15.w,
          ),
          Expanded(
            child: CustomButtonWidget(
              text: "同意退款",
              onTap: () {
                print("同意退款");
                BottomGeneralDialog.showBottomGeneralDialog(
                  context,
                  title: "温馨提示",
                  desc: "同意后将会立即为患者退款，请注意核实服务状态",
                  buttonFontSize: 14.sp,
                  onConfirm: () {
                    print("同意退款");
                    _submitAuditServiceRefundData("2");
                  },
                  onCancel: () {
                    print("拒绝退款");
                  },
                );
              },
              textStyle: TextStyle(fontSize: 14.sp, color: ColorRes.white),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: ColorRes.colorMain, // 添加背景色
              ),
            ),
          ),
          SizedBox(
            width: 15.w,
          ),
          Expanded(
            child: CustomButtonWidget(
              text: "确定完成服务",
              onTap: () {
                print("确定完成服务");
                _confirmFinishServiceBottomDialog();
              },
              textStyle: TextStyle(fontSize: 14.sp, color: ColorRes.white),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: ColorRes.colorMain, // 添加背景色
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 拒绝退款
  _buildRefuseRefundDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              child: Container(
                  height: 280.w,
                  width: double.infinity,
                  decoration: BoxDecoration(color: ColorRes.white, borderRadius: BorderRadius.circular(5.w)),
                  child: Column(
                    children: [
                      SizedBox(height: 22.w),
                      Text('拒绝退款',
                          style: TextStyle(color: ColorRes.color333333, fontSize: 17.sp, fontWeight: FontWeight.bold)),
                      SizedBox(height: 22.w),

                      //////////

                      Container(
                        margin: EdgeInsets.only(right: 15.w, left: 15.w),
                        height: 110.w,
                        padding: EdgeInsets.all(12.w),
                        decoration: BoxDecoration(
                            border: Border.all(color: ColorRes.colord2d2d2, width: 0.5.w),
                            borderRadius: BorderRadius.circular(5.w)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Expanded(
                                child: TextField(
                              controller: _textEditingController,
                              maxLines: null,
                              maxLength: 20,
                              style: TextStyle(fontSize: 14.sp),
                              decoration: const InputDecoration(
                                  contentPadding: EdgeInsets.zero,
                                  isDense: true,
                                  counterText: '',
                                  hintText: '请输入拒绝理由。',
                                  border: InputBorder.none),
                            )),
                          ],
                        ),
                      ),

                      /////////

                      Container(
                        margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.w),
                        child: Text('', style: TextStyle(color: ColorRes.color666666, fontSize: 16.sp)),
                      ),
                      Expanded(child: Container()),
                      Container(color: ColorRes.colorEEF2F5, height: 1),
                      SizedBox(
                        height: 50.w,
                        width: double.infinity,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Expanded(
                              child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    context.pop([0, '']);
                                  },
                                  child: Text('取消',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: ColorRes.color666666, fontSize: 17.sp))),
                            ),
                            Container(
                              width: 1,
                              color: ColorRes.colorEEF2F5,
                            ),
                            Expanded(
                              child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    var string = _textEditingController.text.trim().toString();
                                    if (StringUtils.isEmpty(string)) {
                                      Fluttertoast.showToast(msg: '请输入拒绝理由', gravity: ToastGravity.CENTER);
                                      return;
                                    }
                                    context.pop([1, string]);
                                    _submitAuditServiceRefundData("3");
                                  },
                                  child: Text('确定',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: ColorRes.color518DF6, fontSize: 17.sp))),
                            )
                          ],
                        ),
                      )
                    ],
                  )));
        }).then((value) {});
  }
}
